package com.hhss.qishi.controller.rabbitmq.original;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Auther: zcc
 * @Date: 19-7-19 16:21
 * @Description:
 */
public class ReceiverExchange {

    private final static String QUEUE_NAME = "test_queue_work1";

    private final static String EXCHANGE_NAME = "test_exchange_fanout";

    public static void main(String[] args) throws Exception {
        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 绑定队列到交换机
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                // 捕获消息内容
                String message = new String(body, "UTF-8");
                try {
                    System.out.println(message);
                    // 消息确认
                    channel.basicAck(envelope.getDeliveryTag(), false);
                } catch (Exception e) {
                    // 出现异常，置为true，重新入队。
                    channel.basicAck(envelope.getDeliveryTag(), true);
                    // 出现异常，不重新入队，而是reject入死信队列。
                    //channel.basicReject(envelope.getDeliveryTag(), false);
                }
            }
        };
        // 第二个参数值为false代表关闭RabbitMQ的自动应答机制，改为手动应答。
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}
